package com.example.result.explore

import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class CoroutineExplore {

    suspend fun two(job: Job = SupervisorJob()): String {
        var result = ""
        val ceh = CoroutineExceptionHandler { coroutineContext, throwable ->
            val ans = throwable.message == "async"
            result +=
                "${job.javaClass}:当async{}中抛出异常,调用await()，异常也被传递到了CoroutineExceptionHandler:$ans" + "\n"
        }
        val scope = CoroutineScope(job + ceh)
        scope.launch(ceh) {
            try {
                async {
                    throw Exception("async")
                }.await()
            } catch (e: Exception) {
                val ans = e.message == "async"
                result +=
                    "当async{}中抛出异常,调用await()的地方可以捕获异:${ans}" + "\n"
            }
        }.join()
        return result
    }

    suspend fun one(job: Job = SupervisorJob()): String {
        var result = ""
        val ceh = CoroutineExceptionHandler { coroutineContext, throwable ->
            val ans = throwable.message == "async"
            result +=
                "${job.javaClass}:当async{}中抛出异常,不调用await()，异常也被传递到了CoroutineExceptionHandler:$ans" + "\n"
        }
        val scope = CoroutineScope(job + ceh)
        scope.launch(ceh) {
            try {
                async {
                    throw Exception("async")
                }
            } catch (e: Exception) {
                val ans = e.message == "async"
                result +=
                    "当async{}中抛出异常,调用await()的地方可以捕获异:${ans}" + "\n"
            }
        }.join()
        return result
    }

    suspend fun result(): MutableList<String> {
        val ans = mutableListOf<String>()
        ans.add(one())
        ans.add(two())
        ans.add(one(Job()))
        ans.add(two(Job()))
        return ans
    }
}